/*
 * ******************************************************************************
 *   Copyright (c) 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.demo.fragment;


import it.gmariotti.cardslib.demo.CollectionViewCallbacks;
import it.gmariotti.cardslib.demo.ResourceTable;
import it.gmariotti.cardslib.demo.fragment.nativeview.*;
import it.gmariotti.cardslib.demo.ui.widget.CollectionView;
import it.gmariotti.cardslib.library.Constants;
import it.gmariotti.cardslib.library.internal.base.ArrayAdapter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class NativeDashFragment extends AbilitySlice {
    private CollectionView mCollectionView;

    public interface Callbacks {
        void onTopicSelected(MenuEntry menuEntry, Component clickedView);
    }

    private Callbacks sDummyCallbacks = (menuEntry, clickedView) -> {
        try {
            Class mClass = menuEntry.mClass;
            Intent secondIntent = new Intent();
            // 指定待启动FA的bundleName和abilityName
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("it.gmariotti.cardslib.demo")
                    .withAbilityName(mClass.getName())
                    .build();
            secondIntent.setOperation(operation);
            startAbility(secondIntent); // 通过AbilitySlice的startAbility接口实现启动另一个页面
        } catch (Exception e) {
             HiLog.error(Constants.LABEL_LOG,e.toString());
        }
    };

    private Callbacks mCallbacks = sDummyCallbacks;


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_demo_fragment_nativedash);
        mCollectionView = (CollectionView) findComponentById(ResourceTable.Id_menu_collection_vew);

        final NativeDashAdapter adapter = buildAdapter();
        adapter.setCallbacks(mCallbacks);
        mCollectionView.setCollectionAdapter(adapter);
        mCollectionView.updateInventory(adapter.getInventory());
        mCollectionView.setOnScrollListener((component, i, i1, i2, i3) -> adapter.hideDescriptionToast());
    }


    protected NativeDashAdapter buildAdapter() {
        return new NativeDashAdapter(getAbility(), buildMenuList());
    }


    @Override
    protected void onStop() {
        super.onStop();
        mCallbacks = sDummyCallbacks;
    }


    protected static class NativeDashAdapter extends ArrayAdapter<MenuEntry> implements CollectionViewCallbacks {

        protected final Context mContext;
        private ToastDialog mCurrentToast;
        int TOKEN = 0x1;
        int TOKEN2 = 0x2;
        int TOKEN3 = 0x2;
        private Callbacks mCallbacks;

        public NativeDashAdapter(Context context, List<MenuEntry> objects) {
            super(context, 0, objects);
            mContext = context;
        }

        public CollectionView.Inventory getInventory() {
            CollectionView.Inventory inventory = new CollectionView.Inventory();

            try {
                int size = mContext.getResourceManager().getElement(ResourceTable.Integer_menu_grid_columns).getInteger();
                String label1 = mContext.getResourceManager().getElement(ResourceTable.String_header_title_group1).getString();
                String label2 = mContext.getResourceManager().getElement(ResourceTable.String_header_title_group2).getString();
                String label3 = mContext.getResourceManager().getElement(ResourceTable.String_header_title_group3).getString();

                inventory.addGroup(new CollectionView.InventoryGroup(TOKEN)
                        .setDisplayCols(size)
                        .setItemCount(5)
                        .setHeaderLabel(label1)
                        .setShowHeader(true));

                inventory.addGroup(new CollectionView.InventoryGroup(TOKEN2)
                        .setDisplayCols(size)
                        .setItemCount(6)
                        .setDataIndexStart(5)
                        .setHeaderLabel(label2)
                        .setShowHeader(true));

                inventory.addGroup(new CollectionView.InventoryGroup(TOKEN3)
                        .setDisplayCols(size)
                        .setItemCount(5)
                        .setDataIndexStart(11)
                        .setHeaderLabel(label3)
                        .setShowHeader(true));
            } catch (Exception e) {
                HiLog.error(Constants.LABEL_LOG, "exception:" + e.toString());
            }

            return inventory;
        }

        @Override
        public Component newCollectionHeaderView(Context context, ComponentContainer parent) {
            return LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_item_dashmenu_header, parent, false);
        }

        @Override
        public void bindCollectionHeaderView(Context context, Component view, int groupId, String headerLabel) {
            ((Text) view.findComponentById(ResourceTable.Id_name)).setText(headerLabel);
        }

        @Override
        public Component newCollectionItemView(Context context, int groupId, ComponentContainer parent) {
            return newView(context, parent);
        }

        @Override
        public void bindCollectionItemView(Context context, Component view, int groupId, int indexInGroup, int dataIndex, Object tag) {
            bindView(view, dataIndex);
        }

        @Override
        public Component getComponent(int position, Component convertView, ComponentContainer parent) {
            return null;
        }


        public Component newView(Context context, ComponentContainer parent) {
            Component view = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_item_dashmenu, parent, false);
            ViewHolder holder = new ViewHolder();
            assert view != null;
            holder.name = (Text) view.findComponentById(ResourceTable.Id_name);
            holder.description = (Image) view.findComponentById(ResourceTable.Id_description);
            view.setTag(holder);
            return view;
        }

        public Component bindView(Component view, int position) {
            ViewHolder holder = (ViewHolder) view.getTag();
            final MenuEntry menuEntry = getItem(position);
            final String hashtag;
            try {
                hashtag = mContext.getResourceManager().getElement(menuEntry.titleId).getString();
                holder.name.setText(hashtag);
                ShapeElement shapeElement = new ShapeElement();
                int color = Color.getIntColor(mContext.getResourceManager().getElement(menuEntry.colorId).getString());
                shapeElement.setRgbColor(new RgbColor(color));
                view.setBackground(shapeElement);

                view.setClickedListener(view1 -> {
                    mCallbacks.onTopicSelected(menuEntry, view1);
                });

                final String desc;
                desc = mContext.getResourceManager().getElement(menuEntry.descriptionId).getString();
                if (!desc.isEmpty()) {
                    holder.description.setVisibility(Component.VISIBLE);
                    holder.description.setClickedListener(view12 -> displayDescription(view12, desc));
                } else {
                    holder.description.setVisibility(Component.HIDE);
                }
            } catch (Exception e) {
                HiLog.error(Constants.LABEL_LOG, "exception:" + e.toString());
            }
            return view;
        }

        private void displayDescription(Component view, String desc) {
            hideDescriptionToast();
            mCurrentToast = new ToastDialog(mContext).setText(desc);
            mCurrentToast.show();
            view.announceAccessibility(desc);
        }

        public void hideDescriptionToast() {
            if (mCurrentToast != null) {
                mCurrentToast.cancel();
                mCurrentToast = null;
            }
        }

        public void setCallbacks(Callbacks callbacks) {
            mCallbacks = callbacks;
        }

        private static final class ViewHolder {
            Text name;
            Image description;
        }
    }


    public static class MenuEntry {

        public int titleId;
        public int colorId;
        public int descriptionId;
        public Class mClass;

        public MenuEntry(int titleId, int colorId, int descriptionId, Class aClass) {
            this.titleId = titleId;
            this.colorId = colorId;
            this.descriptionId = descriptionId;
            mClass = aClass;
        }
    }

    private static List<MenuEntry> buildMenuList() {
        ArrayList<MenuEntry> list = new ArrayList<MenuEntry>();
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_base_header, ResourceTable.Color_md_indigo_200, ResourceTable.String_header_title_cardheadersubtitle, NativeHeaderFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_base_shadow, ResourceTable.Color_md_green_300, ResourceTable.String_header_title_cardshadowsubtitle, NativeShadowFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_base_thumbnail, ResourceTable.Color_md_orange_300, ResourceTable.String_header_title_cardthumbnailsubtitle, NativeThumbnailFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_base_card, ResourceTable.Color_md_yellow_700, ResourceTable.String_header_title_cardsubtitle, NativeCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_base_card_expand, ResourceTable.Color_md_cyan_400, ResourceTable.String_header_title_cardexpandsubtitle, NativeCardExpandFragment.class));

        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_material, ResourceTable.Color_md_indigo_600, ResourceTable.String_header_title_cardheadersubtitle, NativeMaterialCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_topcolored, ResourceTable.Color_md_teal_200, ResourceTable.String_header_title_subtitle_ex_topcolored, NativeTopColoredCardFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_misc_cardwithlist, ResourceTable.Color_md_orange_800, ResourceTable.String_header_title_subtitle_cardwithlist, NativeCardWithListFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_gplay, ResourceTable.Color_md_green_300, ResourceTable.String_header_title_cardheadersubtitle, NativeGPlayCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_birthday_card, ResourceTable.Color_md_indigo_A400, ResourceTable.String_header_title_cardheadersubtitle, NativeBirthDayCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_misc_card, ResourceTable.Color_md_green_600, ResourceTable.String_header_title_subtitle_ex_misc, NativeMiscCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_ex_card_changevalue, ResourceTable.Color_md_pink_A200, ResourceTable.String_header_title_subtitle_ex_refresh, NativeChangeValueCardFragment.class));

//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_recyclerView, ResourceTable.Color_md_blue_A200, ResourceTable.String_header_title_subtitle_recyclerview, NativeRecyclerViewFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_base, ResourceTable.Color_md_red_800, ResourceTable.String_header_title_subtitle_lbase, NativeListBaseFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_expandable_card, ResourceTable.Color_md_blue_600, ResourceTable.String_header_title_subtitle_lexpand, NativeListExpandCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_misc_sectioned, ResourceTable.Color_md_indigo_300, ResourceTable.String_header_title_subtitle_sectioned, NativeListSectionedCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_google_play, ResourceTable.Color_md_blue_A200, ResourceTable.String_header_title_subtitle_lgplay, NativeListGplayCardFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_swipe_undo, ResourceTable.Color_md_cyan_700, ResourceTable.String_header_title_subtitle_swipe, NativeListGplayUndoCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_base_different_layout, ResourceTable.Color_md_green_600, ResourceTable.String_header_title_subtitle_ldiff, NativeListDifferentInnerBaseFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_cursor, ResourceTable.Color_md_orange_800, ResourceTable.String_header_title_subtitle_lcursor, NativeListCursorCardFragment.class));
        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_colored, ResourceTable.Color_md_cyan_700, ResourceTable.String_header_title_subtitle_lcolored, NativeListColorFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_grid_base,ResourceTable.Color_md_cyan_700,ResourceTable.String_header_title_subtitle_gbase, NativeGridBaseFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_grid_google_play, ResourceTable.Color_md_red_800, ResourceTable.String_header_title_subtitle_ggplay, NativeGridGplayFragment.class));
//        list.add(new MenuEntry(ResourceTable.String_carddemo_title_tag_list_grid_cursor, ResourceTable.Color_md_brown_400, ResourceTable.String_header_title_subtitle_gcursor, NativeGridCursorCardFragment.class));

        return list;
    }
}
